package logic

import (
	"context"
	"time"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"github.com/eeppee_admin/clouddisk/service/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFileListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFileListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFileListLogic {
	return &UserFileListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFileListLogic) UserFileList(req *types.UserFileListRequest) (resp *types.UserFileListResponse, err error) {
	userFile := make([]*types.UserFile, 0)
	resp = new(types.UserFileListResponse)
	// 分页参数
	pageSize := req.Size
	if pageSize == 0 {
		pageSize = 20 // 默认20
	}
	page := req.Page
	if page == 0 {
		page = 1
	}

	offset := (page - 1) * pageSize

	userStore := new(model.UserStore)
	_, err = l.svcCtx.Engine.Table("userstore").Select("id").
		Where("identity = ?", req.Identity).Get(userStore)

	if err != nil {
		return nil, err
	}

	// 查询用户文件列表
	err = l.svcCtx.Engine.Table("userstore").
		Where("parent_id = ? and user_identity = ?", userStore.Id, userStore.UserIdentity).
		Select("userstore.id, userstore.identity, userstore.store_identity, userstore.ext," + "userstore.name, storepool.path,storepool.size").
		Join("LEFT", "storepool", "userstore.store_identity = storepool.identity").
		Where("userstore.deleted_at = ? OR userstore.deleted_at IS NULL", time.Time{}.Format("2024-12-12 15:01:02")).
		Limit(pageSize, offset).
		Find(&userFile)
	if err != nil {
		return
	}

	// 查询用户文件总数
	cnt, err := l.svcCtx.Engine.Where("parent_id = ? AND user_identity = ?", userStore.Id, userStore.UserIdentity).
		Count(new(model.UserStore))
	if err != nil {
		return
	}

	resp.List = userFile
	resp.Count = cnt

	return
}
